﻿Imports System.IO
Imports System.Reflection

Public Class logInfo
  Public Shared logFileName As String = ""

  ' helper class to log messages on a named files
  Public Overloads Shared Function WriteLog(ByVal slogFileName As String, ByVal msg As String) As System.Exception
    Try
      Dim lf As File
      Dim sw As StreamWriter
      sw = File.AppendText(slogFileName)
      sw.WriteLine(msg)
      sw.Close()
      sw = Nothing
      lf = Nothing
      Return Nothing
    Catch ex As Exception
      Return ex
    End Try
  End Function

  Public Overloads Shared Function WriteLog(ByVal slogFileName As String, ByVal obj As Object) As System.Exception
    Dim logEx As Exception
    logEx = WriteLog(slogFileName, "Object Info:")
    If Not logEx Is Nothing Then
      Return logEx
    End If
    Try
      If obj Is Nothing Then
        WriteLog(slogFileName, "Nothing")
      Else
        WriteLog(slogFileName, obj.GetType.Name)
        WriteLog(slogFileName, "  properties:")
        For Each prop As PropertyInfo In obj.GetType.GetProperties() 'Reflection.BindingFlags.DeclaredOnly Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance
          Try
            WriteLog(slogFileName, CStr(prop.Name.TrimEnd & "[" & prop.PropertyType.Name & "]=" & prop.GetValue(obj, Type.EmptyTypes)))
          Catch ex As Exception
            WriteLog(slogFileName, CStr(prop.Name.TrimEnd & "[" & prop.PropertyType.Name & "]="))
          End Try
        Next
        ' Try to use the tostring method
        Try
          WriteLog(slogFileName, "ToString: " & obj.ToString())
        Catch ex As Exception
          ' Ignore
        End Try
      End If
      Return Nothing
    Catch ex As Exception
      Return ex
    End Try
  End Function

  Public Overloads Shared Function WriteFile(ByVal slogFileName As String, ByVal msg As String) As System.Exception
    Return WriteLog(slogFileName, msg)
  End Function

  Public Overloads Shared Function WriteFile(ByVal slogFileName As String, ByVal obj As Object) As System.Exception
    Return WriteLog(slogFileName, obj)
  End Function

  Public Overloads Shared Function WriteLog(ByVal msg As String) As System.Exception
    If logFileName.Trim.Length = 0 Then
      Return New Exception("log file name not set")
    End If
    Return WriteLog(logFileName, msg)
  End Function

  Public Overloads Shared Function WriteLog(ByVal obj As Object) As System.Exception
    If logFileName.Trim.Length = 0 Then
      Return New Exception("log file name not set")
    End If
    Return WriteLog(logFileName, obj)
  End Function

End Class
